﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AppMain
{
    public enum Trigger_Type
    {
        Awlays,
        Once,
    }

    public delegate void onTriggerBox2D(BaseRole role);

    public class TriggerEntity : BoxRole
    {
        public TriggerEntity(IAttrMap attrMap) : base(attrMap)
        {
        }

        public Trigger_Type triggerType = Trigger_Type.Awlays;
        bool isDie = false;
        HashSet<long> enterSet = new HashSet<long>();

        public override void tick(float frameTime)
        {
            //取到场景里面的所有实体 进行碰撞检测
            BaseScene scene = this.AttrMap.getAttr<BaseScene>(RoleAttr.Scene).Value;
            var ier = scene.map.GetEnumerator();
            while (ier.MoveNext())
            {
                long roleId = ier.Current.Value.UID;
                if (roleId != this.UID)
                {
                    BoxRole role = ier.Current.Value as BoxRole;
                    if (role == null) continue;
                    bool isCollision = Physics.cast2D(this.box3D, role.box3D);
                    if (isCollision)
                    {
                        if (enterSet.Contains(roleId))
                        {
                            onStay(role);
                        }
                        else
                        {
                            onEnter(role);
                            enterSet.Add(roleId);
                            if (this.triggerType == Trigger_Type.Once)
                            {
                                isDie = true;
                            }
                        }
                    }
                    else
                    {
                        if (enterSet.Contains(roleId))
                        {
                            onExit(role);
                            enterSet.Remove(roleId);
                        }
                    }

                }
            }

        }

        private void onEnter(BaseRole role)
        {
            if (!(role is NetRole)) return;
            Console.WriteLine(string.Format("玩家[{0}]踩到了场景{1}触发器", role.AttrMap.getAttr<string>(RoleAttr.NickName).Value,
                role.AttrMap.getAttr<BaseScene>(RoleAttr.Scene).Value.sceneId));
            //切换实体的场景
            long sid = this.AttrMap.getAttr<BaseScene>(RoleAttr.Scene).Value.sceneId == 101002 ? 101003 : 101002;
            EventMgr.Instance.dispatch(EventCmd.Entity_Enter_Trigger, role, sid);
        }
        private void onStay(BaseRole role)
        {

        }
        private void onExit(BaseRole role)
        {

        }

        public bool canRemove()
        {
            return this.isDie;
        }

        public override void dispose()
        {

        }


    }

}
